#!/opt/api-umbrella/bin/api-umbrella-exec resty
-- vi: ft=lua :

local OrderedMap = require "pl.OrderedMap"
local json_decode = require("cjson").decode
local lyaml = require "lyaml"
local pretty = require "pl.pretty"
local writefile = require("pl.utils").writefile

local countries_handle = io.popen("curl -fsSL https://raw.githubusercontent.com/hexorx/countries/v2.1.2/lib/countries/cache/countries.json")
local countries_result = countries_handle:read("*a")
local countries_data = json_decode(countries_result)

local countries = OrderedMap()
for key, value in pairs(countries_data) do
  countries:set(key, value["name"])
end
countries:sort()

local us_handle = io.popen("curl -fsSL https://raw.githubusercontent.com/hexorx/countries/v2.1.2/lib/countries/data/subdivisions/US.yaml")
local us_result = us_handle:read("*a")
local us_data = lyaml.load(us_result)

local subdivisions = {
  US = OrderedMap(),
}
for key, value in pairs(us_data) do
  subdivisions["US"]:set(key, value["name"])
end
subdivisions["US"]:sort()

local output = [[-- Do not manually edit: Generated by ./scripts/generate_countries_data
-- based on data from https://github.com/hexorx/countries

local _M = {}

_M.countries = ]] .. pretty.write(countries) .. [[


_M.subdivisions = ]] .. pretty.write(subdivisions) .. [[


return _M]]

writefile("src/api-umbrella/web-app/utils/countries.lua", output)
